﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Tb.App.API.Applications.Command.Cultivation;
using Tb.App.Domain.Rabbit.Cultivation;
using Tb.App.ErrorCode;
using Tb.App.Infrastructure.Interfaces;

namespace Tb.App.API.Applications.CommandHandler.Cultivation
{
    /// <summary>
    /// 添加养殖信息-命令
    /// </summary>
    public class AddCultivationCommandHandler : IRequestHandler<AddCultivationCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<CultivationModel> culRep;
        private readonly IMapper mapper;
        private readonly ILogger<AddCultivationCommandHandler> logger;

        public AddCultivationCommandHandler(IBaseRepository<CultivationModel> culRep,
            IMapper mapper,ILogger<AddCultivationCommandHandler> logger)
        {
            this.culRep = culRep;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(AddCultivationCommand request, CancellationToken cancellationToken)
        {
            //添加养殖信息实现思路,前端的信息根据同一批次,进行添加,显示,
            //在此处,添加前先确保有没有数据,有的话逻辑删除,再添加新数据,显示出最新的一条数据
            ApiResult<int> result = new ApiResult<int>();
            // 获取数据库的执行策略
            var executionStrategy = culRep.DB.Database.CreateExecutionStrategy();
            // 使用执行策略执行事务操作
            await executionStrategy.ExecuteAsync(async () =>
            {
                using (var tran = await culRep.DB.Database.BeginTransactionAsync(cancellationToken))
                {
                    try
                    {

                        var entity = culRep.GetAll().Where(x => x.Batch == request.Batch && !x.IsDel).ToList();
                        entity.ForEach(o =>
                        {
                            o.IsDel = true;
                        });
                        await culRep.UpdateRange(entity);

                        var culs = mapper.Map<CultivationModel>(request);
                        var a = await culRep.AddAsync(culs);
                        if (a > 0)
                        {
                            result.Code = ApiEnum.添加成功;
                            result.Message = ApiEnum.添加成功.ToString();
                            result.Data = a;

                        }
                        else
                        {
                            result.Code = ApiEnum.添加失败;
                            result.Message = ApiEnum.添加失败.ToString();
                            result.Data = a;

                        }
                        await tran.CommitAsync(cancellationToken);
                    }
                    catch (Exception)
                    {
                        result.Code = ApiEnum.添加失败;
                        result.Message = ApiEnum.添加失败.ToString();
                        await tran.RollbackAsync(cancellationToken);
                        throw;
                    }
                }
            });

            
            return result;

        }
    }
}
